package com.andox.fn.inf.rpc.rest.serializer;

import org.apache.commons.codec.binary.Base64;
import org.nustaq.serialization.FSTConfiguration;

import com.andox.fn.inf.rpc.rest.extension.Extension;

/**   
 * @ClassName:   FSTSerializer   
 * @Description: TODO  
 * @author:      Andox
 * @date:        2019年7月31日 下午4:17:39   
 *     
 */
@Extension("fst")
public class FSTSerializer implements Serializer {
	//public static final FSTSerializer DEFAULT_INSTANCE = new FSTSerializer();
	
	static FSTConfiguration configuration = FSTConfiguration
			// .createDefaultConfiguration();
					.createStructConfiguration();
	@Override
	public byte[] serialize(Object object) {
		if (object == null)
			return null;
		return configuration.asByteArray(object);
	}

	@Override
	public String serializeAsString(Object object) {
		if (object == null)
			return null;

		return Base64.encodeBase64String(this.serialize(object));
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T unserialize(byte[] source, Class<T> clazz) {
		if (source == null || source.length == 0)
			return null;
		
		return (T)configuration.asObject(source);
	}

	@Override
	public <T> T unserializeFromString(String source, Class<T> clazz) {
		if (source == null || source.length() == 0){
			return null;
		}
		
		return this.unserialize(Base64.decodeBase64(source), clazz);
	}

}
